package com.yuexun.dhdoctor.module.meetingNew.ui;

import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSONArray;
import com.yuexun.dhdoctor.R;
import com.yuexun.dhdoctor.base.BaseEntity;
import com.yuexun.dhdoctor.base.BaseKJActivity;
import com.yuexun.dhdoctor.base.bean.model.HelpFileData;
import com.yuexun.dhdoctor.base.bean.model.HelpFileEntity;
import com.yuexun.dhdoctor.config.AppConfig;
import com.yuexun.dhdoctor.module.Contract.bean.ChildDepartmentsBean;
import com.yuexun.dhdoctor.module.Contract.bean.GroupGroupData;
import com.yuexun.dhdoctor.module.Contract.bean.People;
import com.yuexun.dhdoctor.module.commun.adapter.AddMemberAdapter;
import com.yuexun.dhdoctor.module.commun.ui.Act_Choice_Member;
import com.yuexun.dhdoctor.module.commun.ui.Act_DepartAndGroup;
import com.yuexun.dhdoctor.module.commun.ui.Act_Department;
import com.yuexun.dhdoctor.module.email.adapter.MailFileAdapter;
import com.yuexun.dhdoctor.module.email.bean.MailFileDataBean;
import com.yuexun.dhdoctor.module.email.bean.UploadBean;
import com.yuexun.dhdoctor.module.email.model.impl.UploadModel;
import com.yuexun.dhdoctor.module.email.presenter.impl.UploadPresenter;
import com.yuexun.dhdoctor.module.email.ui.view.IUploadView;
import com.yuexun.dhdoctor.module.meetingNew.bean.MeetingNewRoleBean;
import com.yuexun.dhdoctor.module.meetingNew.bean.MeetingNewRoomBean;
import com.yuexun.dhdoctor.module.meetingNew.bean.MeetingNewRoomBeanNew;
import com.yuexun.dhdoctor.module.meetingNew.bean.MeetingNewSignAddBean;
import com.yuexun.dhdoctor.module.meetingNew.bean.MeetingNewTypeBean;
import com.yuexun.dhdoctor.module.meetingNew.model.impl.MeetingNewModel;
import com.yuexun.dhdoctor.module.meetingNew.presenter.impl.MeetingNewAddPresenter;
import com.yuexun.dhdoctor.module.meetingNew.presenter.impl.MeetingNewJudgeMemberPresenter;
import com.yuexun.dhdoctor.module.meetingNew.presenter.impl.MeetingNewTypeListPresenter;
import com.yuexun.dhdoctor.module.meetingNew.ui.view.IMeetingNewAddView;
import com.yuexun.dhdoctor.module.meetingNew.ui.view.IMeetingNewJudgeMemberView;
import com.yuexun.dhdoctor.module.meetingNew.ui.view.IMeetingNewTypeListView;
import com.yuexun.dhdoctor.util.GetPathFromUri4kitkat;
import com.yuexun.dhdoctor.widget.ActionSheetDialog;
import com.yuexun.dhdoctor.widget.ClickOneDialog;
import com.yuexun.dhdoctor.widget.FixedSwipeListView;
import com.yuexun.dhdoctor.widget.FlowLayout;
import com.yuexun.dhdoctor.widget.LoadingDialog;
import com.yuexun.dhdoctor.widget.MeetingDialog;
import com.yuexun.dhdoctor.widget.ModelAddViewNew;
import com.yuexun.dhdoctor.widget.ToastDialog;
import com.yuexun.dhdoctor.widget.UploadDialog;
import com.yuexun.dhdoctor.widget.pickerUtil.CustomDatePicker;


import org.kymjs.kjframe.ui.ViewInject;
import org.kymjs.kjframe.utils.PreferenceHelper;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by wangt on 2017/12/18.
 */

public class Act_MeetingNew_Add extends BaseKJActivity implements IUploadView, IMeetingNewAddView,
        IMeetingNewJudgeMemberView, IMeetingNewTypeListView {

    @Bind(R.id.et_title)
    EditText etTitle;
    @Bind(R.id.tv_start_date)
    TextView tvStartDate;
    @Bind(R.id.tv_end_date)
    TextView tvEndDate;
    @Bind(R.id.tv_adder)
    TextView tvAdder;
    @Bind(R.id.ll_customize_adder)
    LinearLayout llCustomizeAdder;
    @Bind(R.id.et_customize_adder)
    EditText etCustomizeAdder;
    @Bind(R.id.viewGroup)
    FlowLayout flowLayout;

    @Bind(R.id.rl_type)
    RelativeLayout rlType;
    @Bind(R.id.tv_type)
    TextView tvType;
    @Bind(R.id.model_view)
    LinearLayout modelView;

    @Bind(R.id.et_compere)
    EditText etCompere;
    @Bind(R.id.et_clerk)
    EditText etClerk;

    @Bind(R.id.et_content)
    EditText etContent;
    @Bind(R.id.grid_join)
    GridView grid;
    @Bind(R.id.et_person_join)
    TextView etPerson;

    @Bind(R.id.ll_ready)
    LinearLayout llReady;
    @Bind(R.id.et_ready_content)
    EditText etReadyContent;
    @Bind(R.id.grid_ready)
    GridView gridReady;
    @Bind(R.id.et_person_ready)
    TextView etPersonReady;

    @Bind(R.id.tv_sign_deprtment)
    TextView tvSignDeprtment;
    @Bind(R.id.et_sign_num)
    EditText etSignNum;
    @Bind(R.id.ll_sign_add)
    LinearLayout llSignAdd;
    @Bind(R.id.flv_attachment)
    FixedSwipeListView flvAttachment;
    @Bind(R.id.et_otherMember)
    EditText etOtherMember;
    @Bind(R.id.ll_other_member)
    LinearLayout llOtherMember;

    private UploadDialog uploadDialog;
    private UploadPresenter presenter_upload;
    //上传的附件
    private ArrayList<MailFileDataBean> mailFileDataBeans = new ArrayList<>();
    private MailFileAdapter fileAdapter;

    private MeetingNewTypeListPresenter typeListPresenter;
    private MeetingNewAddPresenter presenter;
    private MeetingNewJudgeMemberPresenter judgeMemberPresenter;

    //选取的与会人员list
    private ArrayList<People> joinPeoples = new ArrayList<>();
    //选取的准备人员list
    private ArrayList<People> readyPeoples = new ArrayList<>();

    //地点列表
    private ArrayList<MeetingNewRoomBean> roomList = new ArrayList<>();
    //可见性列表
    private ArrayList<MeetingNewRoleBean> roleList = new ArrayList<>();
    //应签到部门
    private ArrayList<MeetingNewSignAddBean> signList = new ArrayList<>();
    //类型list
    private ArrayList<MeetingNewTypeBean> typeList = new ArrayList<>();
    //当前选中地点
    private MeetingNewRoomBean nowRoom;
    //当前选中类型
    private MeetingNewTypeBean nowType;

    //当前类型详情
    private HelpFileEntity helpFileEntity;
    //类型模板
    private ArrayList<HelpFileData> dtlList = new ArrayList<>();

    //附件原路径
    private String img_path;

    private LoadingDialog loadingDialog;
    private ClickOneDialog clickOneDialog;
    private MeetingDialog dialog;

    //新版会议：展示二维码、有准备人员、与会人员冲突
    private boolean isNewMeeting = false;
    //有会议模板
    private boolean isHaveType = false;

    //当前点击的应签到部门view
    private View nowDepartmentView;

    @Override
    public void setRootView() {
        super.setRootView();
        setContentView(R.layout.act_meetingnew_add);
        ButterKnife.bind(this);
    }

    @Override
    public void initData() {
        super.initData();
        loadingDialog = new LoadingDialog(this);
        loadingDialog.setCanceledOnTouchOutside(false);
        uploadDialog = new UploadDialog(this);
        presenter_upload = new UploadPresenter(new UploadModel(), this);
        typeListPresenter = new MeetingNewTypeListPresenter(new MeetingNewModel(), this);
        presenter = new MeetingNewAddPresenter(new MeetingNewModel(), this);
        judgeMemberPresenter = new MeetingNewJudgeMemberPresenter(new MeetingNewModel(), this);

        clickOneDialog = new ClickOneDialog(this).builder().setContent("总附件容量过大，请处理后提交!")
                .setCancelable(false).setCanceledOnTouchOutside(false);
        clickOneDialog.setCallBack(new ClickOneDialog.ICallBack() {
            @Override
            public void sureCallback(String content) {
                clickOneDialog.dismiss();
            }
        });

        isNewMeeting = true;
        llReady.setVisibility(View.VISIBLE);

        isHaveType = true;
        rlType.setVisibility(View.VISIBLE);
        ApiGetTypeList();

        llOtherMember.setVisibility(View.VISIBLE);

        ApiGetRoleList();
    }

    @Override
    @OnClick({R.id.back, R.id.right, R.id.tv_start_date, R.id.tv_end_date, R.id.tv_adder, R.id.rl_roomuser,
            R.id.tv_type, R.id.img_choose_join, R.id.img_choose_ready, R.id.img_sign_add,
            R.id.tv_sign_deprtment, R.id.ll_extra_file})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.back:
                finish();
                break;
            case R.id.right:
                if (TextUtils.isEmpty(etTitle.getText().toString())) {
                    ViewInject.toast("请输入主题");
                    break;
                }
                if (TextUtils.isEmpty(tvStartDate.getText().toString())) {
                    ViewInject.toast("请选择会议开始时间");
                    break;
                }
                if (TextUtils.isEmpty(tvEndDate.getText().toString())) {
                    ViewInject.toast("请选择会议结束时间");
                    break;
                }
                if (nowRoom == null) {
                    ViewInject.toast("请选择会议地点");
                    break;
                } else {
                    if (nowRoom.getRoomId().equals("0") && TextUtils.isEmpty(etCustomizeAdder.getText().toString())) {
                        ViewInject.toast("请输入自定义地点");
                        break;
                    }
                }
                if (isHaveType && TextUtils.isEmpty(tvType.getText().toString())) {
                    ViewInject.toast("请选择会议类型");
                    break;
                }
                if (TextUtils.isEmpty(etContent.getText().toString())) {
                    ViewInject.toast("请输入会议内容");
                    break;
                }
                if (joinPeoples.size() == 0) {
                    ViewInject.toast("请选择与会人员");
                    break;
                }
                if (!getSignDepartment()) {
                    break;
                }
                if (getFileSize(mailFileDataBeans) > 20) {
                    clickOneDialog.show();
                    break;
                }

                if (isNewMeeting) {
                    ApiGetJudgeData();
                } else {
                    ApiCreate();
                }
                break;
            case R.id.tv_start_date:
                selectDate(1);
                break;
            case R.id.tv_end_date:
                selectDate(2);
                break;
            case R.id.tv_adder:
                if (TextUtils.isEmpty(tvStartDate.getText().toString())) {
                    ViewInject.toast("请先选择会议开始时间");
                    break;
                }
                if (TextUtils.isEmpty(tvEndDate.getText().toString())) {
                    ViewInject.toast("请先选择会议结束时间");
                    break;
                }
                selectRoom();
                break;
            case R.id.tv_type:
                selectTypeDialog();
                break;
            case R.id.rl_roomuser:
                Intent intent_1 = new Intent(this, Act_MeetingNew_RoomUse.class);
                intent_1.putExtra("tag", 1);
                startActivityForResult(intent_1, 100);
                break;
            case R.id.img_choose_join:
                addMember(1, joinPeoples);
                break;
            case R.id.img_choose_ready:
                addMember(2, readyPeoples);
                break;
            case R.id.img_sign_add:
                addSign();
                break;
            case R.id.tv_sign_deprtment:
                ArrayList departList = new ArrayList<>();
                if (!TextUtils.isEmpty(tvSignDeprtment.getText().toString())) {
                    if (tvSignDeprtment.getTag().toString().split("_")[0].equals("1")) { //部门
                        ChildDepartmentsBean item = new ChildDepartmentsBean();
                        item.setDepartment_id(Integer.valueOf(tvSignDeprtment.getTag().toString().split("_")[1]));
                        item.setDepartment_name(tvSignDeprtment.getText().toString());
                        departList.add(item);
                    } else if (tvSignDeprtment.getTag().toString().split("_")[0].equals("2")) { //群组
                        GroupGroupData item = new GroupGroupData();
                        item.setGroupId(tvSignDeprtment.getTag().toString().split("_")[1]);
                        item.setTitle(tvSignDeprtment.getText().toString());
                        departList.add(item);
                    }
                }

                Bundle bundle = new Bundle();
                Intent intent;
                if (isHaveType) {
                    intent = new Intent(aty, Act_DepartAndGroup.class);
                } else {
                    intent = new Intent(aty, Act_Department.class);
                }
                bundle.putSerializable("departmentBeans", departList);
                bundle.putInt("fromWhere", 2);
                bundle.putInt("isSelectMe", 1);
                intent.putExtras(bundle);
                aty.startActivityForResult(intent, 1);
                break;
            case R.id.ll_extra_file:
                select_file();
                break;
        }
    }

    //请求会议模板类型列表
    private void ApiGetTypeList() {
        Map<String, String> params = new HashMap<>();
        params.put("sessionUuid", PreferenceHelper.readString(aty, AppConfig.USER_INFO, AppConfig.SESSION_ID));
        typeListPresenter.getTypeList(params);
    }

    //请求会议类型详情
    private void ApiGetTypeDetail() {
        Map<String, String> params = new HashMap<>();
        params.put("sessionUuid", PreferenceHelper.readString(aty, AppConfig.USER_INFO, AppConfig.SESSION_ID));
        params.put("configId", nowType.getConfigId() + "");
        typeListPresenter.getTypeDetail(params);
    }

    //请求会议地点列表
    private void ApiGetRoomList(String startDate, String endDate) {
        loadingDialog.show();
        Map<String, String> params = new HashMap<>();
        params.put("sessionUuid", PreferenceHelper.readString(aty, AppConfig.USER_INFO, AppConfig.SESSION_ID));
        params.put("pageIndex", "1");
        params.put("pageSize", "999");
        params.put("startDate", startDate);
        params.put("endDate", endDate);
        presenter.getRoomList(params);
    }

    //请求可见性列表
    private void ApiGetRoleList() {
        Map<String, String> params = new HashMap<>();
        params.put("sessionUuid", PreferenceHelper.readString(aty, AppConfig.USER_INFO, AppConfig.SESSION_ID));
        params.put("configFlag", "1");
        params.put("pageIndex", "1");
        params.put("pageSize", "9999");
        presenter.getRoleList(params);
    }

    //请求会议冲突人员
    private void ApiGetJudgeData() {
        loadingDialog.show();
        //与会人员
        String[] strPeopleIdArr = new String[joinPeoples.size()];
        for (int i = 0; i < joinPeoples.size(); i++) {
            strPeopleIdArr[i] = joinPeoples.get(i).getUserId();
        }

        Map<String, String> params = new HashMap<>();
        params.put("sessionUuid", PreferenceHelper.readString(aty, AppConfig.USER_INFO, AppConfig.SESSION_ID));
        params.put("startDate", tvStartDate.getText().toString());
        params.put("endDate", tvEndDate.getText().toString());
        judgeMemberPresenter.getJudgeMember(strPeopleIdArr, params);
    }

    //发起会议
    private void ApiCreate() {
        //与会人员
        String[] strPeopleIdArr = new String[joinPeoples.size()];
        StringBuilder strPeopleName = new StringBuilder();
        for (int i = 0; i < joinPeoples.size(); i++) {
            strPeopleIdArr[i] = joinPeoples.get(i).getUserId();
            strPeopleName.append(joinPeoples.get(i).getUserName()).append(";");
        }

        //准备人员
        String[] strReadyPeopleIdArr = new String[readyPeoples.size()];
        StringBuilder strReadyPeopleName = new StringBuilder();
        for (int i = 0; i < readyPeoples.size(); i++) {
            strReadyPeopleIdArr[i] = readyPeoples.get(i).getUserId();
            strReadyPeopleName.append(readyPeoples.get(i).getUserName()).append(";");
        }

        //可见性
        StringBuilder strVisibleRole = new StringBuilder();
        for (int i = 0; i < roleList.size(); i++) {
            if (roleList.get(i).isSelect()) {
                strVisibleRole.append("'").append(roleList.get(i).getRoleId()).append("'").append(";");
            }
        }

        //签到部门、群组
        ArrayList<String> arrDeptId = new ArrayList<>();
        ArrayList<String> arrDeptSignCount = new ArrayList<>();
        ArrayList<String> arrGroupId = new ArrayList<>();
        ArrayList<String> arrGroupSignCount = new ArrayList<>();

        for (int i = 0; i < signList.size(); i++) {
            if (signList.get(i).getType().equals("1")) {
                arrDeptId.add(signList.get(i).getDepartId());
                arrDeptSignCount.add(signList.get(i).getPeopleNum());
            } else if (signList.get(i).getType().equals("2")) {
                arrGroupId.add(signList.get(i).getDepartId());
                arrGroupSignCount.add(signList.get(i).getPeopleNum());
            }
        }
        String[] strDeptId = new String[arrDeptId.size()];
        String[] strDeptSignCount = new String[arrDeptSignCount.size()];
        String[] strGroupId = new String[arrGroupId.size()];
        String[] strGroupSignCount = new String[arrGroupSignCount.size()];

        arrDeptId.toArray(strDeptId);
        arrDeptSignCount.toArray(strDeptSignCount);
        arrGroupId.toArray(strGroupId);
        arrGroupSignCount.toArray(strGroupSignCount);

        //附件
        StringBuilder strFile = new StringBuilder();
        for (int i = 0; i < mailFileDataBeans.size(); i++) {
            strFile.append(mailFileDataBeans.get(i).getFileUuid()).append(";");
        }

        Map<String, String> params = new HashMap<>();
        params.put("sessionUuid", PreferenceHelper.readString(aty, AppConfig.USER_INFO, AppConfig.SESSION_ID));
        params.put("meetingName", etTitle.getText().toString());
        params.put("startDatetime", tvStartDate.getText().toString());
        params.put("endDatetime", tvEndDate.getText().toString());
        if (nowRoom.getRoomId().equals("0")) {
            params.put("roomId", "0");
            params.put("roomName", etCustomizeAdder.getText().toString());
        } else {
            params.put("roomId", nowRoom.getRoomId());
            params.put("roomName", nowRoom.getRoomName());
        }
        params.put("content", etContent.getText().toString());
        params.put("compere", etCompere.getText().toString());
        params.put("clerk", etClerk.getText().toString());
        params.put("participant", strPeopleName.toString());
        params.put("visibleRole", strVisibleRole.toString());
        params.put("fileUrl", strFile.toString());
        params.put("readyContent", etReadyContent.getText().toString());
        params.put("readyNames", strReadyPeopleName.toString());

        if (isHaveType) {
            params.put("configId", nowType.getConfigId() + "");
            params.put("configName", nowType.getConfigName());
            if (dtlList != null && !new ModelAddViewNew(aty, dtlList).isEmpty()) {
                params.put("dtlJson", JSONArray.toJSONString(dtlList));
            } else {
                return;
            }
        }
        params.put("otherMember", etOtherMember.getText().toString());
        presenter.createMeeting(strPeopleIdArr, strReadyPeopleIdArr, strDeptId, strDeptSignCount, strGroupId, strGroupSignCount, params);
        loadingDialog.show();
    }

    @Override
    public void showRoomList(BaseEntity<MeetingNewRoomBean> bean) {
        if (bean.getStatus().equals("200")) {
            roomList = bean.getDatas();
            MeetingNewRoomBean other = new MeetingNewRoomBean();
            other.setRoomId("0");
            other.setRoomName("自定义");
            roomList.add(other);
        } else {
            ViewInject.toast(bean.getMessage());
        }
        if (loadingDialog.isShowing()) {
            loadingDialog.dismiss();
        }
    }

    @Override
    public void showRoleList(BaseEntity<MeetingNewRoleBean> bean) {
        if (bean.getStatus().equals("200")) {
            roleList = bean.getDatas();

            for (MeetingNewRoleBean item : roleList) {
                item.setSelect(true);
            }

            for (final MeetingNewRoleBean item : roleList) {
                if (item.getRoleId() != 1) {
                    View view = LayoutInflater.from(this).inflate(R.layout.item_select_checkbox, null);
                    CheckBox checkBox = (CheckBox) view.findViewById(R.id.checkbox);
                    checkBox.setText(item.getRoleName());
                    checkBox.setChecked(item.isSelect());
                    LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
                    params.setMargins(0, 10, 10, 0);
                    flowLayout.addView(view, params);

                    checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                        @Override
                        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                            item.setSelect(isChecked);
                        }
                    });
                }
            }
        }
    }

    @Override
    public void getTypeList(BaseEntity<MeetingNewTypeBean> bean) {
        if (bean.getStatus().equals("200")) {
            typeList = bean.getDatas();
            MeetingNewTypeBean datasEntity = new MeetingNewTypeBean();
            datasEntity.setConfigId(-999);
            datasEntity.setConfigName("其他");
            typeList.add(datasEntity);
        }
    }

    @Override
    public void getTypeDetail(BaseEntity<HelpFileEntity> bean) {
        if (bean.getStatus().equals("200")) {
            if (bean.getDatas().size() > 0) {
                helpFileEntity = bean.getDatas().get(0);
                dtlList.clear();
                new ModelAddViewNew(aty, dtlList).showView(helpFileEntity, modelView);
            } else {
                modelView.setVisibility(View.GONE);
            }
        }
    }

    @Override
    public void getJudgeMember(BaseEntity<String> bean) {
        if (bean.getStatus().equals("200")) {
            if (bean.getDatas().size() == 0) {
                ApiCreate();
            } else {
                showDilaog(bean.getDatas());
            }
        }

        if (loadingDialog.isShowing()) {
            loadingDialog.dismiss();
        }
    }

    @Override
    public void createMeeting(BaseEntity<String> bean) {
        if (bean.getStatus().equals("200")) {
            setResult(100);
            finish();
        } else {
            ViewInject.toast("发起失败");
        }
        loadingDialog.show();
    }

    @Override
    public void showRoomList2(BaseEntity<MeetingNewRoomBeanNew> bean) {

    }

    //选择时间 1：开始时间  2：结束时间
    private void selectDate(int id) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.CHINA);
        String now = sdf.format(new Date());
        if (id == 1) {
            CustomDatePicker customDatePicker = new CustomDatePicker(this, new CustomDatePicker.ResultHandler() {
                @Override
                public void handle(String time) {
                    if (TextUtils.isEmpty(tvEndDate.getText().toString())) {
                        tvStartDate.setText(time);
                    } else {
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.CHINA);
                        Date startDate = null;
                        Date endDate = null;
                        try {
                            startDate = sdf.parse(time);
                            endDate = sdf.parse(tvEndDate.getText().toString());
                        } catch (ParseException e) {
                            e.printStackTrace();
                        }
                        if (startDate.after(endDate)) {
                            ViewInject.toast("不能晚于结束时间");
                        } else {
                            tvStartDate.setText(time);
                            ApiGetRoomList(time, tvEndDate.getText().toString());
                        }
                    }
                }
            }, "2010-01-01 00:00", now); // 初始化日期格式请用：yyyy-MM-dd HH:mm，否则不能正常运行
            customDatePicker.setIsLoop(true); // 不允许循环滚动
            customDatePicker.setCancelable(true);
            customDatePicker.showSpecificDate(true);
            customDatePicker.showSpecificTime(true);
            customDatePicker.show(now);
        } else {
            CustomDatePicker customDatePicker = new CustomDatePicker(this, new CustomDatePicker.ResultHandler() {
                @Override
                public void handle(String time) {
                    if (TextUtils.isEmpty(tvStartDate.getText().toString())) {
                        tvEndDate.setText(time);
                    } else {
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.CHINA);
                        Date startDate = null;
                        Date endDate = null;
                        try {
                            startDate = sdf.parse(tvStartDate.getText().toString());
                            endDate = sdf.parse(time);
                        } catch (ParseException e) {
                            e.printStackTrace();
                        }
                        if (endDate.before(startDate)) {
                            ViewInject.toast("不能早于开始时间");
                        } else {
                            tvEndDate.setText(time);
                            ApiGetRoomList(tvStartDate.getText().toString(), time);
                        }
                    }
                }
            }, "2010-01-01 00:00", now); // 初始化日期格式请用：yyyy-MM-dd HH:mm，否则不能正常运行
            customDatePicker.setIsLoop(true); // 不允许循环滚动
            customDatePicker.setCancelable(true);
            customDatePicker.showSpecificDate(true);
            customDatePicker.showSpecificTime(true);
            customDatePicker.show(now);
        }
    }

    //选择会议地点
    private void selectRoom() {
        ActionSheetDialog actionSheetDialog;
        actionSheetDialog = new ActionSheetDialog(this).builder()
                .setType(2)
                .setCancelable(true)
                .setCanceledOnTouchOutside(true);


        for (int i = 0; i < roomList.size(); i++) {
            actionSheetDialog.addSheetItem(roomList.get(i).getRoomName(), ActionSheetDialog.SheetItemColor.Blue,
                    new ActionSheetDialog.OnSheetItemClickListener() {
                        @Override
                        public void onClick(int which) {
                            nowRoom = roomList.get(which - 1);
                            tvAdder.setText(nowRoom.getRoomName());
                            if (nowRoom.getRoomId().equals("0")) {
                                llCustomizeAdder.setVisibility(View.VISIBLE);
                            } else {
                                llCustomizeAdder.setVisibility(View.GONE);
                            }
                        }
                    });
        }
        actionSheetDialog.show();
    }

    //选择模板类型
    private void selectTypeDialog() {
        ActionSheetDialog actionSheetDialog;
        actionSheetDialog = new ActionSheetDialog(this).builder()
                .setCancelable(true)
                .setCanceledOnTouchOutside(true);

        for (int i = 0; i < typeList.size(); i++) {
            actionSheetDialog.addSheetItem(typeList.get(i).getConfigName(), ActionSheetDialog.SheetItemColor.Blue,
                    new ActionSheetDialog.OnSheetItemClickListener() {
                        @Override
                        public void onClick(int which) {
                            nowType = typeList.get(which - 1);
                            tvType.setText(nowType.getConfigName());

                            modelView.removeAllViews();
                            if (typeList.get(which - 1).getConfigId() != -999) {
                                modelView.setVisibility(View.VISIBLE);
                                ApiGetTypeDetail();
                            } else {
                                modelView.setVisibility(View.GONE);
                                if (dtlList.size() > 0) {
                                    dtlList.clear();
                                }
                            }
                        }
                    });
        }
        actionSheetDialog.show();
    }

    //显示人员提示
    private void showDilaog(List<String> peoples) {
        if (loadingDialog.isShowing()) {
            loadingDialog.dismiss();
        }
        StringBuilder strPeoples = new StringBuilder();
        for (String str : peoples) {
            strPeoples.append(str).append(";");
        }

        dialog = new MeetingDialog(this);
        dialog.builder().setContent(strPeoples.toString())
                .setTitle("以下人员会议时间有冲突!\n确认发起会议?");
        dialog.setCallBack(new MeetingDialog.ICallBack() {
            @Override
            public void cancelCallback() {
                dialog.dismiss();
            }

            @Override
            public void sureCallback() {
                ApiCreate();
            }
        });
        dialog.show();
    }

    //选择接收对象
    private void addMember(int type, ArrayList<People> peoples) {
        Bundle bundle = new Bundle();
        Intent intent = new Intent(this, Act_Choice_Member.class);
        bundle.putSerializable("persons", peoples);
        bundle.putString("title", "发起会议");
        bundle.putString("type", "多选");
        bundle.putInt("isSelectMe", 1);
        intent.putExtras(bundle);
        startActivityForResult(intent, type);
    }

    //添加签到
    private void addSign() {
        View view = LayoutInflater.from(this).inflate(R.layout.item_meetingnew_add_sign, null);
        final LinearLayout llSign = (LinearLayout) view.findViewById(R.id.item_ll_sign);
        ImageView imgSignLess = (ImageView) view.findViewById(R.id.item_img_sign_less);
        ImageView imgSignAdd = (ImageView) view.findViewById(R.id.item_img_sign_add);
        final TextView tvSignDeprtment = (TextView) view.findViewById(R.id.item_tv_sign_deprtment);
        EditText etSignNum = (EditText) view.findViewById(R.id.item_et_sign_num);

        imgSignLess.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                llSignAdd.removeView(llSign);
                showEndAdd();
            }
        });

        imgSignAdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                addSign();
            }
        });

        tvSignDeprtment.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                nowDepartmentView = v;
                ArrayList departList = new ArrayList<>();
                if (!TextUtils.isEmpty(tvSignDeprtment.getText().toString())) {
                    if (tvSignDeprtment.getTag().toString().split("_")[0].equals("1")) { //部门
                        ChildDepartmentsBean item = new ChildDepartmentsBean();
                        item.setDepartment_id(Integer.valueOf(tvSignDeprtment.getTag().toString().split("_")[1]));
                        item.setDepartment_name(tvSignDeprtment.getText().toString());
                        departList.add(item);
                    } else if (tvSignDeprtment.getTag().toString().split("_")[0].equals("2")) { //群组
                        GroupGroupData item = new GroupGroupData();
                        item.setGroupId(tvSignDeprtment.getTag().toString().split("_")[1]);
                        item.setTitle(tvSignDeprtment.getText().toString());
                        departList.add(item);
                    }
                }

                Bundle bundle = new Bundle();
                Intent intent;
                if (isHaveType) {
                    intent = new Intent(aty, Act_DepartAndGroup.class);
                } else {
                    intent = new Intent(aty, Act_Department.class);
                }
                bundle.putSerializable("departmentBeans", departList);
                bundle.putInt("fromWhere", 2);
                bundle.putInt("isSelectMe", 1);
                intent.putExtras(bundle);
                aty.startActivityForResult(intent, 2);
            }
        });

        llSignAdd.addView(view);

        showEndAdd();
    }

    //最后一条显示加号
    private void showEndAdd() {
        int childcount = llSignAdd.getChildCount();
        for (int i = 0; i < childcount; i++) {
            View view = llSignAdd.getChildAt(i);
            ImageView imgSignAdd = (ImageView) view.findViewById(R.id.item_img_sign_add);

            imgSignAdd.setVisibility(View.INVISIBLE);
            if (i == (childcount - 1)) {
                imgSignAdd.setVisibility(View.VISIBLE);
            }
        }
    }

    //获取签到部门、人数
    private boolean getSignDepartment() {
        signList.clear();
        if (TextUtils.isEmpty(tvSignDeprtment.getText().toString()) && !TextUtils.isEmpty(etSignNum.getText().toString())) {
            ViewInject.toast("请选择应签到部门");
            return false;
        } else if (!TextUtils.isEmpty(tvSignDeprtment.getText().toString()) && TextUtils.isEmpty(etSignNum.getText().toString())) {
            ViewInject.toast("请填写应签到人数");
            return false;
        } else if (!TextUtils.isEmpty(tvSignDeprtment.getText().toString()) && !TextUtils.isEmpty(etSignNum.getText().toString())) {
            MeetingNewSignAddBean item = new MeetingNewSignAddBean();
            item.setDepartId(tvSignDeprtment.getTag().toString().split("_")[1]);
            item.setPeopleNum(etSignNum.getText().toString());
            item.setType(tvSignDeprtment.getTag().toString().split("_")[0]);
            signList.add(item);
        }

        int childcount = llSignAdd.getChildCount();
        for (int i = 0; i < childcount; i++) {
            View view = llSignAdd.getChildAt(i);
            TextView tvDepartment = (TextView) view.findViewById(R.id.item_tv_sign_deprtment);
            EditText etNum = (EditText) view.findViewById(R.id.item_et_sign_num);

            if (TextUtils.isEmpty(tvDepartment.getText().toString()) && !TextUtils.isEmpty(etNum.getText().toString())) {
                ViewInject.toast("请选择应签到部门");
                return false;
            } else if (!TextUtils.isEmpty(tvDepartment.getText().toString()) && TextUtils.isEmpty(etNum.getText().toString())) {
                ViewInject.toast("请填写应签到人数");
                return false;
            } else if (!TextUtils.isEmpty(tvDepartment.getText().toString()) && !TextUtils.isEmpty(etNum.getText().toString())) {
                MeetingNewSignAddBean item = new MeetingNewSignAddBean();
                item.setDepartId(tvDepartment.getTag().toString().split("_")[1]);
                item.setPeopleNum(etNum.getText().toString());
                item.setType(tvDepartment.getTag().toString().split("_")[0]);
                signList.add(item);
            }
        }

        return true;
    }

    //获取附件大小
    private double getFileSize(List<MailFileDataBean> fileDataBean) {
        Double allSize = 0.00;
        for (MailFileDataBean item : fileDataBean) {
            allSize = allSize + (Double.valueOf(item.getFileSize()) / 1024.00 / 1024.00);
        }
        return allSize;
    }

    //从设备读取文件
    private void select_file() {
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
//        intent.setType("*/*");//设置类型，我这里是任意类型，任意后缀的可以这样写。
        intent.setType("*/*");
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        try {
            startActivityForResult(intent, 1);
        } catch (ActivityNotFoundException ex) {
            new ToastDialog(this, "未找到文件管理应用，请安装文件管理应用后再试").show();
        }
    }

    @Override
    public void uploadDialogStatus(int status) {
        switch (status) {
            case AppConfig.SHOW_DIALOG:
                uploadDialog.setCanceledOnTouchOutside(false);
                uploadDialog.show();
                break;
            case AppConfig.DISMISS_DIALOG:
                uploadDialog.dismiss();
                ViewInject.toast("上传成功!");
                break;
        }
    }

    @Override
    public void updateFile(UploadBean uploadBean) {
        flvAttachment.setVisibility(View.VISIBLE);
        if (mailFileDataBeans.size() == 0) {
            uploadBean.getData().get(0).setFileUrl(img_path);
            mailFileDataBeans.add(uploadBean.getData().get(0));
            fileAdapter = new MailFileAdapter(this, mailFileDataBeans, true);
            flvAttachment.setAdapter(fileAdapter);
        } else {
            uploadBean.getData().get(0).setFileUrl(img_path);
            mailFileDataBeans.add(uploadBean.getData().get(0));
            fileAdapter.notifyDataSetChanged();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data != null) {
            switch (resultCode) {
                case 10000:
                    List<People> peopleList = (ArrayList<People>) data.getExtras().getSerializable("persons");
                    if (requestCode == 1) {
                        joinPeoples.clear();
                        joinPeoples.addAll(peopleList);
                        if (joinPeoples.size() > 0) {
                            etPerson.setVisibility(View.GONE);
                        } else {
                            etPerson.setVisibility(View.VISIBLE);
                        }
                        setGridView(grid, joinPeoples);
                    } else if (requestCode == 2) {
                        readyPeoples.clear();
                        readyPeoples.addAll(peopleList);
                        if (readyPeoples.size() > 0) {
                            etPersonReady.setVisibility(View.GONE);
                        } else {
                            etPersonReady.setVisibility(View.VISIBLE);
                        }
                        setGridView(gridReady, readyPeoples);
                    }
                    break;
                case Activity.RESULT_OK:
                    Uri uri = data.getData();//得到uri，后面就是将uri转化成file的过程。
                    img_path = GetPathFromUri4kitkat.getPath(this, uri);
                    presenter_upload.uploadFile(img_path);
                    break;
                case 10001://选择部门回调
                    if (requestCode == 1) {//第一个签到部门
                        List<ChildDepartmentsBean> departmentBeans = (ArrayList<ChildDepartmentsBean>) data.getExtras().getSerializable("departmentBeans");
                        tvSignDeprtment.setText(departmentBeans.get(0).getDepartment_name());
                        tvSignDeprtment.setTag("1_" + departmentBeans.get(0).getDepartment_id());
                    } else {//签到部门
                        List<ChildDepartmentsBean> departmentBeans = (ArrayList<ChildDepartmentsBean>) data.getExtras().getSerializable("departmentBeans");
                        ((TextView) nowDepartmentView).setText(departmentBeans.get(0).getDepartment_name());
                        nowDepartmentView.setTag("1_" + departmentBeans.get(0).getDepartment_id());
                    }
                    break;
                case 10004://选择部门、群组回调
                    if (requestCode == 1) {//第一个签到部门
                        ArrayList departmentBeans = (ArrayList) data.getExtras().getSerializable("departmentBeans");
                        if (departmentBeans.get(0) instanceof ChildDepartmentsBean) {//部门
                            tvSignDeprtment.setText(((ChildDepartmentsBean) departmentBeans.get(0)).getDepartment_name());
                            tvSignDeprtment.setTag("1_" + ((ChildDepartmentsBean) departmentBeans.get(0)).getDepartment_id());
                        } else if (departmentBeans.get(0) instanceof GroupGroupData) {//群组
                            tvSignDeprtment.setText(((GroupGroupData) departmentBeans.get(0)).getTitle());
                            tvSignDeprtment.setTag("2_" + ((GroupGroupData) departmentBeans.get(0)).getGroupId());
                        }
                    } else if (requestCode == 2) {//签到部门
                        ArrayList departmentBeans = (ArrayList) data.getExtras().getSerializable("departmentBeans");
                        if (departmentBeans.get(0) instanceof ChildDepartmentsBean) {//部门
                            ((TextView) nowDepartmentView).setText(((ChildDepartmentsBean) departmentBeans.get(0)).getDepartment_name());
                            nowDepartmentView.setTag("1_" + ((ChildDepartmentsBean) departmentBeans.get(0)).getDepartment_id());
                        } else if (departmentBeans.get(0) instanceof GroupGroupData) {//群组
                            ((TextView) nowDepartmentView).setText(((GroupGroupData) departmentBeans.get(0)).getTitle());
                            nowDepartmentView.setTag("2_" + ((GroupGroupData) departmentBeans.get(0)).getGroupId());
                        }
                    }
                    break;
                case 0x001:
                    nowRoom = (MeetingNewRoomBean) data.getExtras().getSerializable("room");
                    String startTime = data.getExtras().getString("startTime");
                    String endTime = data.getExtras().getString("endTime");
                    String date = data.getExtras().getString("date");

                    tvStartDate.setText(date + " " + startTime);
                    tvEndDate.setText(date + " " + endTime);
                    tvAdder.setText(nowRoom.getRoomName());

                    ApiGetRoomList(date + " " + startTime, date + " " + endTime);
                    break;
            }
        }
    }

    private void setGridView(GridView view, ArrayList<People> peoples) {
        int size = peoples.size();

        int length = 80;

        DisplayMetrics dm = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dm);
        float density = dm.density;
        int gridviewWidth = (int) (size * (length + 4) * density);
        int itemWidth = (int) (length * density);

        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                gridviewWidth, LinearLayout.LayoutParams.MATCH_PARENT);
        view.setLayoutParams(params); // 重点
        view.setColumnWidth(itemWidth); // 重点
        view.setHorizontalSpacing(5); // 间距
        view.setStretchMode(GridView.NO_STRETCH);
        view.setNumColumns(size); // 重点

        AddMemberAdapter adapter = new AddMemberAdapter(view, peoples, R.layout.item_send_addmember);
        view.setAdapter(adapter);
    }

}
